package cn.jx.asc.socket;

/*
 *负责向终端发送指令
 *
 */

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

import org.json.JSONException;
import org.json.JSONObject;


public class SendInstruct {
    InputStreamReader in = null;
    OutputStreamWriter out = null;
    int id = -1;
    Scanner sc;

    public SendInstruct(int i,InputStreamReader inp,OutputStreamWriter o) {
        id = i;
        out = o;
        in = inp;
    }

    public boolean send() {

        //获取指令
        List listInstruct = (List) InstructAndResult.getInstructs(id);
        for(int i=0;i<listInstruct.size();i++) {
            try {
                //发送指令
                String inst = ((Instruct)listInstruct.get(i)).getInstruct().toString();
                out.write(inst);
                out.flush();

                //获取结果
                sc = new Scanner(in);
                String line = sc.nextLine();

                //判断返回时结果还是心跳
                JSONObject resultJson = new JSONObject(line);
//				int flag = resultJson.getInt("flag");
//				if(flag != 0) {
//					//将结果插入结果集
//
//				}
                int resultID = ((Instruct)listInstruct.get(i)).getInstructID();
                InstructAndResult.insertResult(resultID, resultJson);

                //将数据输入handle处理，
                new HandleData(id, resultJson).handle();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //发送成功，删除指令
        InstructAndResult.deleteInstructs(id);

        //发送成功返回true
        return true;
    }
}
